package com.sky.service.user.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hxc.pay.CommonPayTemplate;
import com.hxc.pay.JsapiPayTemplate;
import com.hxc.pay.wx.utils.SignUtils;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.exception.NoCourierException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ParameterIsNullException;
import com.sky.mapper.admin.MerchantMapper;
import com.sky.mapper.user.*;
import com.sky.pojo.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.common.OrderDispatchService;
import com.sky.service.user.OrderService;
import com.sky.utils.MapUtils;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {


    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private MerchantMapper merchantMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;


    @Autowired
    private JsapiPayTemplate jsapiPayTemplate;

    @Autowired
    private CommonPayTemplate commonPayTemplate;

    @Autowired
    private SignUtils signUtils;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Result<String> getEstimatedDeliveryTime(Long shopId, String customerAddress) {
        // 预计送达时间 = 当前时间 +  菜品制作时间 + 配送时间 + 预留时间（10分钟）
        //1.菜品的制作时间  分钟
        Integer totalMakeTime = shoppingCartMapper.selectTotalMakeTimeByUserId(BaseContext.getCurrentId());
        //2.商家新信息
        Merchant merchant = merchantMapper.selectById(shopId);
        //3.计算2地之间的配送时间
        Integer costTime = MapUtils.baoiduTwoPointCostTime(merchant.getShopAddress(), customerAddress);
        //计算时间
        LocalDateTime deliveryTime = LocalDateTime.now().plusSeconds(totalMakeTime * 60 + costTime + 600);

        return Result.success(deliveryTime.toString());
    }

    @Override
    @Transactional
    public Result<OrderSubmitVO> submit(OrdersSubmitDTO dto) {
//        创建orders
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto,orders);
//        填充属性
        orders.setNumber(UUID.randomUUID().toString().replaceAll("-",""));
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
          // 查询地址簿信息
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());
        Integer totalMakeTime = shoppingCartMapper.selectTotalMakeTimeByUserId(BaseContext.getCurrentId());
        orders.setMealTime(LocalDateTime.now().plusMinutes(totalMakeTime));
        //        1.保存订单信息
        orderMapper.save(orders);
//                创建orderDetials
        List<OrderDetail> orderDetailList = new ArrayList<>();
//        查询当前用户的购物车数据
        ShoppingCart shoppingCart = ShoppingCart.builder().
                                        userId(BaseContext.getCurrentId()).
                                        build();
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.selectByConditon(shoppingCart);
//                属性填充
        shoppingCartList.forEach(shoppingCart1 -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart1,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        });
//        2.保存订单详情
        orderDetailMapper.batchSave(orderDetailList);
//        3.清空购物车
        shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());

        //构建返回数据
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .orderAmount(orders.getAmount())
                .build();
        return Result.success(orderSubmitVO);
    }

    @Override
    public Result<OrderPaymentVO> payment(OrdersPaymentDTO dto) {

        //调用小程序下单接口得到预支付标识
        User user = userMapper.selectById(BaseContext.getCurrentId());
        // {"prepay_id":"xxxxxxx"}
        String prepayIdJson = jsapiPayTemplate.createOrder(user.getOpenid(), 1, "苍穹外卖订单", dto.getOrderNumber());
        String packageStr = "prepay_id="+ JSON.parseObject(prepayIdJson, Map.class).get("prepay_id").toString();
        //封装OrderPaymentVo需要的5个参数
        String orderPaymentVoJsonStr = signUtils.sign(packageStr);
        OrderPaymentVO vo = JSON.parseObject(orderPaymentVoJsonStr, OrderPaymentVO.class);

        return Result.success(vo);
    }

    /**
     * 用户端订单分页查询
     *
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */
    public PageResult pageQuery4User(int pageNum, int pageSize, Integer status) {
        // 设置分页
        PageHelper.startPage(pageNum, pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        // 分页条件查询
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList();

        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long orderId = orders.getId();// 订单id

                // 查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), list);
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    public OrderVO details(Long id) {
        // 根据id查询订单
        Orders orders = orderMapper.getById(id);

        // 查询该订单对应的菜品/套餐明细
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将该订单及其详情封装到OrderVO并返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
    }

    /**
     * 再来一单
     *
     * @param id
     */
    public void repetition(Long id) {
        // 查询当前用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        // 将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        // 将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    /**
     * 用户取消订单
     *
     * @param id
     */
    public void userCancelById(Long id) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (ordersDB.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());

        // 订单处于待接单状态下取消，需要进行退款
        if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //调用微信支付退款接口

            commonPayTemplate.refund(1,1,orders.getNumber(),orders.getNumber());
            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }
        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED_ORDER);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.updateOrderPaySuccess(orders);
    }

    @Override
    public Result<PageResult> conditionSearch(OrdersPageQueryDTO dto) {

        //1.分页查询
        PageHelper.startPage(dto.getPage(),dto.getPageSize());

        //2.多条件动态sql  多表关联查询结果
        Page<OrderVO> page = orderMapper.conditionSearch(dto);

        //3.封装返回结果即可
        PageResult pageResult = new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(page.getResult());
        return Result.success(pageResult);
    }

//    @Override
//    public Result<OrderStatisticsVO> statistics() {
//
//
//        long l1 = System.currentTimeMillis();
//        //   耗时 = （发送sql+sql执行时间+返回时间）*6
//        Integer waiting4MerchantReceiveOrders = orderMapper.selectCountByStatus(Orders.TO_BE_CONFIRMED);
//        Integer waitng4RiderReceiveOrders = orderMapper.selectCountByStatus(Orders.CONFIRMED);
//        Integer toBeDeliveryOnProgressOrders = orderMapper.selectCountByStatus(Orders.TOBEPICKEDUP);
//        Integer toBeArrivedOrders = orderMapper.selectCountByStatus(Orders.TOBEDELIVERED);
//        Integer completedOrders = orderMapper.selectCountByStatus(Orders.COMPLETE_ORDER);
//        Integer canceledOrders = orderMapper.selectCountByStatus(Orders.CANCELLED_ORDER);
//        long l2 = System.currentTimeMillis();
//        System.out.println("------------统计耗时:"+(l2-l1));
//        OrderStatisticsVO vo = OrderStatisticsVO.builder()
//                .waiting4MerchantReceiveOrders(waiting4MerchantReceiveOrders)
//                .waitng4RiderReceiveOrders(waitng4RiderReceiveOrders)
//                .toBeDeliveryOnProgressOrders(toBeDeliveryOnProgressOrders)
//                .toBeArrivedOrders(toBeArrivedOrders)
//                .completedOrders(completedOrders)
//                .canceledOrders(canceledOrders)
//                .build();
//        return Result.success(vo);
//    }


    @Autowired
    private ThreadPoolExecutor threadPool;

//    @Override
//    public Result<OrderStatisticsVO> statistics() {
//
//        long l1 = System.currentTimeMillis();
//             //耗时 =  Max((发送+执行+返回))
//        Future<Integer> future1 = threadPool.submit(() -> {
//            return orderMapper.selectCountByStatus(Orders.TO_BE_CONFIRMED);
//        });
//
//        Future<Integer> future2 = threadPool.submit(() -> {
//            return orderMapper.selectCountByStatus(Orders.CONFIRMED);
//        });
//        Future<Integer> future3 = threadPool.submit(() -> {
//            return orderMapper.selectCountByStatus(Orders.TOBEPICKEDUP);
//        });
//        Future<Integer> future4 = threadPool.submit(() -> {
//            return orderMapper.selectCountByStatus(Orders.TOBEDELIVERED);
//        });
//        Future<Integer> future5 = threadPool.submit(() -> {
//            return orderMapper.selectCountByStatus(Orders.COMPLETE_ORDER);
//        });
//        Future<Integer> future6 = threadPool.submit(() -> {
//            return orderMapper.selectCountByStatus(Orders.CANCELLED_ORDER);
//        });
//
//
//        Integer waiting4MerchantReceiveOrders = 0;
//        Integer waitng4RiderReceiveOrders = 0;
//        Integer toBeDeliveryOnProgressOrders = 0;
//        Integer toBeArrivedOrders = 0;
//        Integer completedOrders = 0;
//        Integer canceledOrders = 0;
//        try {
//            waiting4MerchantReceiveOrders = future1.get();
//            waitng4RiderReceiveOrders = future2.get();
//            toBeDeliveryOnProgressOrders = future3.get();
//            toBeArrivedOrders = future4.get();
//            completedOrders = future5.get();
//            canceledOrders = future6.get();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        Long l2 = System.currentTimeMillis();
//
//        System.out.println("------------统计耗时:"+(l2-l1));
//        OrderStatisticsVO vo = OrderStatisticsVO.builder()
//                .waiting4MerchantReceiveOrders(waiting4MerchantReceiveOrders)
//                .waitng4RiderReceiveOrders(waitng4RiderReceiveOrders)
//                .toBeDeliveryOnProgressOrders(toBeDeliveryOnProgressOrders)
//                .toBeArrivedOrders(toBeArrivedOrders)
//                .completedOrders(completedOrders)
//                .canceledOrders(canceledOrders)
//                .build();
//        return Result.success(vo);
//    }


//    @Override
//    public Result<OrderStatisticsVO> statistics() {
//
//
//        //一条sql查询个状态的统计数量：
//        Integer waiting4MerchantReceiveOrders = 0;
//        Integer waitng4RiderReceiveOrders = 0;
//        Integer toBeDeliveryOnProgressOrders = 0;
//        Integer toBeArrivedOrders = 0;
//        Integer completedOrders = 0;
//        Integer canceledOrders = 0;
//        //将结果取出来封装即可
//        /*
//            [
//                {status:2,total:26},
//                {status:3,total:26},
//                {status:4,total:26},
//                {status:5,total:26},
//                {status:6,total:26},
//                {status:7,total:26}
//            ]
//
//            -->
//            map
//            {
//                2:26，
//                3:48,
//                4:60,
//                5:33,
//                6:55,
//                7:20
//            }
//         */
//        List<Map> maps = orderMapper.selectAllStatusCount();
//        for(Map map:maps) {
//            Integer status = (Integer) map.get("status");
//            Long total = (Long) map.get("total");
//            switch (status) {
//                case 2:
//                    waiting4MerchantReceiveOrders = total.intValue();
//                    break;
//                case 3:
//                    waitng4RiderReceiveOrders = total.intValue();
//                    break;
//                case 4:
//                    toBeDeliveryOnProgressOrders = total.intValue();
//                    break;
//                case 5:
//                    toBeArrivedOrders = total.intValue();
//                    break;
//                case 6:
//                    completedOrders = total.intValue();
//                    break;
//                case 7:
//                    canceledOrders = total.intValue();
//                    break;
//            }
//        };
//
//
//
//        OrderStatisticsVO vo = OrderStatisticsVO.builder()
//        .waiting4MerchantReceiveOrders(waiting4MerchantReceiveOrders)
//        .waitng4RiderReceiveOrders(waitng4RiderReceiveOrders)
//        .toBeDeliveryOnProgressOrders(toBeDeliveryOnProgressOrders)
//        .toBeArrivedOrders(toBeArrivedOrders)
//        .completedOrders(completedOrders)
//        .canceledOrders(canceledOrders)
//        .build();
//        return Result.success(vo);
//
//    }


    @Override
    public Result<OrderStatisticsVO> statistics() {
        OrderStatisticsVO vo =orderMapper.selectAllStatusCount2();
        return Result.success(vo);
    }

    @Override
    public Result<OrderVO> adminOrderDetails(Long orderId) {

        OrderVO orderVO = orderMapper.adminOrderDetails(orderId);
        return Result.success(orderVO);
    }

    @Override
    public Result<String> adminCancelOrder(OrdersCancelDTO dto) {
        Orders dbOrders = orderMapper.getById(dto.getId());
        //退款
        commonPayTemplate.refund(1,1,dbOrders.getNumber(),dbOrders.getNumber());
        //1.修改order表 、status,cancel_reason 、cancel_time
        Orders orders = new Orders();
        orders.setStatus(Orders.CANCELLING);
        orders.setCancelReason(dto.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orders.setId(dto.getId());
        orderMapper.updateCancellingOrders(orders);
        return Result.success();
    }


    @Autowired
    private OrderDispatchService orderDispatchService;
    @Override
    public Result<Courier> confirm(OrdersConfirmDTO dto) {
        //0.验参
        if(dto.getId()==null){
            throw new ParameterIsNullException("参数不能为空");
        }

        //1.找骑手 -- 自动派单
        Courier courier = orderDispatchService.dispatch(dto.getId(),null,null);

        if(courier==null){
            //继续寻找
            for(int i=0;i<3;i++){
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("----第"+(i+1)+"次寻找骑手---");
                courier = orderDispatchService.dispatch(dto.getId(),null,null);
                if(courier!=null){
                    break;
                }
            }
        }

        if(courier==null){
            throw new NoCourierException("暂时找不到骑手，请稍后再试");
        }


        //2.修改订单的状态即可
        Orders orders = new Orders();

        orders.setStatus(Orders.CONFIRMED);
        orders.setId(dto.getId());
        orderMapper.updateMerchantConfirmStatusById(orders);

        return Result.success(courier);
    }




}
